package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggid.path}")
    private String path;

    //文件上传
    @PostMapping("/upload")
    public R<String> upLoad(MultipartFile file) throws IOException {
        //得到客户端传过来的文件名
        String fileName = file.getOriginalFilename();
        //切割得到文件名的后缀  .png
        String substringFilename = fileName.substring(fileName.lastIndexOf("."));
        //创建UUid 得到随机的文件名 +文件名后缀
        String resultFileName = UUID.randomUUID().toString() + substringFilename;
        //判断保存到本地的路径是否存在  不存在创建,存在跳过
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //将用户上传的文件保存到本地路径下
        file.transferTo(new File(path + resultFileName));
        return R.success(resultFileName);
    }

    //文件下载
    @GetMapping("/download")
    public R<String> downLoad(String name, HttpServletResponse response) throws IOException {
        //读取用户传过来文件名,配合path路径关联本地文件
        FileInputStream fis = new FileInputStream(new File(path + name));
        ServletOutputStream ous = response.getOutputStream();
//        int len = 0;
//        byte[] bytes = new byte[1024];
//        while ((len = fis.read(bytes)) != -1) {
//            response.getOutputStream().write(bytes, 0, len);
//        }
//        fis.close();
        //将输入流数据传输给输出流
        IOUtils.copy(fis, ous);
        fis.close();
        return R.success(name);
    }
}
